package com.bootdo.app.controller;

import com.bootdo.app.htmlVO.customer.MyUserInfo;
import com.bootdo.app.htmlVO.customer.TixianUserInfo;
import com.bootdo.app.htmlVO.order.OrderProductItemsDetails;
import com.bootdo.app.htmlVO.order.UserOrderDetail;
import com.bootdo.app.service.AppUserInfoService;
import com.bootdo.app.utils.AppUtilXML;
import com.bootdo.app.utils.MathUtil;
import com.bootdo.app.utils.MyMath;
import com.bootdo.app.utils.redis.AppRedisUtil;
import com.bootdo.app.utils.returnresponse.ServerResponse;
import com.bootdo.appsystem.domain.*;
import com.bootdo.appsystem.service.*;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 【@author 】 @fan
 * 【@Email  】 mooncluyed@outlook.com
 * 【类解释  】
 * 【@Date   】 2018/5/12 0012
 **/
@Controller
@RequestMapping("/app/user/")
public class AppUserInfoController extends BaseController{

    @Autowired
    private AppUserInfoService appUserInfoService;
    @Autowired
    private SellerService sellerService;
    @Autowired
    private UserdetailsService userdetailsService;
    @Autowired
    private UseraccountService useraccountService;
    @Autowired
    private UserbankcardService userbankcardService;
    @Autowired
    private ShouruService shouruService;
    @Autowired
    private BanksService banksService;
    @Autowired
    private UsershouruService usershouruService;
    @Autowired
    private TixianService tixianService;
    @Autowired
    private OrderproductService orderproductService;
    @Autowired
    private OrderproductitemsService orderproductitemsService;
    @Autowired
    private ProducesinfoService producesinfoService;
    @Autowired
    private EvaluateService evaluateService;
    @Autowired
    private OrderaddressinfoService orderaddressinfoService;



//    去我的页面
    @GetMapping("tomy")
    public String toMy(){
        return "app/my/my";
    }

//    去我的商家页面
    @GetMapping("toseller")
    public String toSeller(){
        return  "app/seller/seller";
    }

//    去身份认证页面
    @GetMapping("touserrenzheng")
    public String toUserRenzheng(){
        return "app/my/idcard/idCard";
    }

//    去身份认证页面
    @GetMapping("touserrenzhengpass")
    public String toUserRenzhengPass(){
        return "app/my/idcard/idCardPass";
    }

//    我的推广用户
    @GetMapping("myChildUser")
    public String toMyChildUser(){
        return "app/my/spreadUser";
    }

//    我的推广用户
    @GetMapping("myChildSeller")
    public String toMyChildSeller(){
        return "app/my/spreadSeller";
    }

//    我的推广二维码
    @GetMapping("myqrCode")
    public String toMyqrCode(){
        return "app/my/qrCode";
    }

//    手机认证页面
    @GetMapping("toApplyPhone")
    public String toApplyPhone() {
        return "app/my/phone/phone";
    }

//    提现申请页面
    @GetMapping("toDesposit")
    public String toDesposit() {
        return "app/my/desposit";
    }

//    提现记录页面
    @GetMapping("toDespositlist")
    public String toDespositlist(){
        return "app/my/despositlist";
    }

//    提现记录页面
    @GetMapping("toEditUserInfo")
    public String toEditUserInfo(){
        return "app/my/userinfo/userInfo";
    }

//    去用户订单列表
    @GetMapping("toUserOrderList")
    public String toUserOrderList(){
        return "app/my/order/userOrder";
    }

//    订单信息列表
    @ResponseBody
    @PostMapping("msgOrderList")
    public ServerResponse<PageUtils> msgOrderList(@RequestParam Map<String, Object> params){
        UseraccountDO sessionCustomer = (UseraccountDO)this.getRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        params.put("uid" , sessionCustomer.getUid());

        Query query = new Query(params);
        List<OrderproductDO> list = orderproductService.list(query);
        int total = orderproductService.count(query);

        PageUtils pageUtils = new PageUtils(list, total);
        return ServerResponse.createBySuccess(pageUtils);
    }


    // 去用户订单详情页
    @GetMapping("toUserOrderDetail")
    public String toUserOrderDetail(String orderCode , Model model){
        ArrayList<UserOrderDetail> userOrderDetailArrayList = new ArrayList<UserOrderDetail>();
        //        根据订单号获取订单列表
        List<OrderproductDO> orderproductDOList = orderproductService.getByOrderCode(orderCode);
        //        循环数据
        for (OrderproductDO orderproductDO : orderproductDOList){
            HashMap<String, Object> map = new HashMap<>();
            map.put("oid",orderproductDO.getOid());
            List<OrderproductitemsDO> list = orderproductitemsService.list(map);

            //     订单详情及数据
            ArrayList<OrderProductItemsDetails> orderProductItemsDetailsList = new ArrayList<OrderProductItemsDetails>();

            for (OrderproductitemsDO orderproductitemsDO : list) {
                //      创建一个新的订单对象存放数据
                OrderProductItemsDetails orderProductItemsDetails = new OrderProductItemsDetails();
                //      获取订单商品详情
                ProducesinfoDO producesinfoDO = producesinfoService.get(orderproductitemsDO.getPid());
                //      获取评价列表
                EvaluateDO evaluateByOrderProductitem = evaluateService.getEvaluateByOrderProductitem(orderproductitemsDO, orderproductDO.getUid());

                orderProductItemsDetails.setEvaluateDO(evaluateByOrderProductitem);
                orderProductItemsDetails.setOrderproductitemsDO(orderproductitemsDO);
                orderProductItemsDetails.setProducesinfoDO(producesinfoDO);
                orderProductItemsDetailsList.add(orderProductItemsDetails);
            }
            //创建一个用户订单详情对象，存放数据
            UserOrderDetail userOrderDetail = new UserOrderDetail();
            userOrderDetail.setOrderProductItemsDetailsList(orderProductItemsDetailsList);
            userOrderDetail.setOrderproductDO(orderproductDO);

            userOrderDetailArrayList.add(userOrderDetail);
        }

        //获取用户地址信息
        OrderaddressinfoDO address = orderaddressinfoService.getByOrderCode(orderCode);

        model.addAttribute("address",address);
        model.addAttribute("userOrderDetailArrayList",userOrderDetailArrayList);
        return "app/my/order/orderDetail";
    }


//    提现申请列表数据
    @ResponseBody
    @GetMapping("msgDespositlist")
    public ServerResponse<PageUtils> msgDespositlist(@RequestParam Map<String, Object> params){
        Query query = new Query(params);
        UseraccountDO sessionCustomer = (UseraccountDO)this.getRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        query.put("uid" , sessionCustomer.getUid());
        List<TixianDO> list = tixianService.list(query);
        int total = tixianService.count(query);
        PageUtils pageUtils = new PageUtils(list, total);
        return ServerResponse.createBySuccess(pageUtils);
    }



//    提现信息
    @ResponseBody
    @PostMapping("msgDesposit")
    public ServerResponse msgDesposit(){
        UseraccountDO useraccountDO = (UseraccountDO) HttpContextUtils.getHttpServletRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        //获取用户信息
        UseraccountDO user = useraccountService.get(useraccountDO.getUid());
        //获取用户提现申请信息
        UserbankcardDO userBankcard = userbankcardService.getByUid(useraccountDO.getUid());
        //银行列表
        List<BanksDO> banksList = AppRedisUtil.get("banksList");
        if(banksList == null){
            banksList = banksService.list(null);
            AppRedisUtil.put("banksList" , banksList);
        }
        //用户收支信息
        UsershouruDO usershouru = usershouruService.getByUid(useraccountDO.getUid());

        TixianUserInfo tixianUserInfo = new TixianUserInfo(user, userBankcard, banksList, usershouru);

        return ServerResponse.createBySuccess(tixianUserInfo);
    }

//    提现申请
    @ResponseBody
    @PostMapping("applyDesposit")
    public ServerResponse applyDesposit(TixianDO tixianDO,String payword){
        try {
            payword = MD5Utils.encrypt(AppUtilXML.SCOKED_NUMBER, payword);
            UseraccountDO user = (UseraccountDO)HttpContextUtils.getSessionObject(AppUtilXML.SESSION_CUSTOMER);
            user = useraccountService.get(user.getUid());
            if (user.getPayword() == null || user.getPayword().equals("")) {
//                user.setPassword(payword);
                UseraccountDO useraccountDO = new UseraccountDO();
                useraccountDO.setPayword(payword);
                useraccountDO.setUid(user.getUid());
                useraccountService.update(useraccountDO);
            }else {
                if(!user.getPayword().equals(payword)){
                    return ServerResponse.createByErrorCodeMessage(409,"密码输入错误");
                 }
            }
            Double lastMoney = MyMath.sub(0 , tixianDO.getMoney());

            tixianDO.setUid(user.getUid());
            tixianDO.setAddtime(new Date());
            tixianDO.setStatus(0);
            if(user.getSellerid() == null){
                tixianDO.setOutmoney(tixianDO.getMoney() * 0.95);
            }
            //创建新的提现信息
            tixianService.save(tixianDO);

            //给用户余额减钱
            useraccountService.addMoneyNotAll(user.getUid(),lastMoney);

            //修改用户银行卡信息
            UserbankcardDO userbankcard = userbankcardService.getByUid(user.getUid());
            userbankcard.setBankname(tixianDO.getBankname());
            userbankcard.setBankcardid(tixianDO.getBankcardid());
            userbankcard.setBankrealname(tixianDO.getBankrealname());
            userbankcardService.update(userbankcard);

            //收入表信息增加
            ShouruDO shouru = new ShouruDO().tixianShouru(user.getUid(), lastMoney);
            shouruService.save(shouru);

            //用户收支情况修改
            UsershouruDO usershouru = usershouruService.getByUid(user.getUid());
            usershouru.setTixian(MyMath.add(usershouru.getTixian(),lastMoney));
            usershouruService.update(usershouru);

            return ServerResponse.createBySuccess();
        }catch (RuntimeException e) {
            e.printStackTrace();
            return ServerResponse.createByError();
        }
    }



//    我的身份认证状态
    @ResponseBody
    @PostMapping("idcardInfo")
    public ServerResponse<String> msgIdcardInfo(){
        UseraccountDO useraccountDO = (UseraccountDO)HttpContextUtils.getHttpServletRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        UserdetailsDO byUid = userdetailsService.getByUid(useraccountDO.getUid());
        if(byUid == null) {
            return ServerResponse.createByError();
        }
        return ServerResponse.createBySuccess(byUid.getIdcardstatus().toString());
    }

//    保存我的身份认证信息
    @ResponseBody
    @PostMapping("insMyIDcardInfo")
    public ServerResponse insMyIDcardInfo(UserdetailsDO userdetailsDO){
        UseraccountDO useraccountDO = (UseraccountDO)HttpContextUtils.getHttpServletRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        UserdetailsDO byUid = userdetailsService.getByUid(useraccountDO.getUid());
        if (byUid != null) {
            byUid.setZheng(userdetailsDO.getZheng());
            byUid.setFan(userdetailsDO.getFan());
            byUid.setIdcard(userdetailsDO.getIdcard());
            byUid.setIdcardaddtime(new Date());
            byUid.setIdcardstatus(10);
            byUid.setGender(userdetailsDO.getGender());
            byUid.setRealname(userdetailsDO.getRealname());
            int update = userdetailsService.update(byUid);
            if (update > 0) {
                return ServerResponse.createBySuccess();
            }
        } else {
            userdetailsDO.setIdcardaddtime(new Date());
            userdetailsDO.setUid(useraccountDO.getUid());
            userdetailsDO.setIdcardstatus(10);
            int save = userdetailsService.save(userdetailsDO);
            if (save > 0) {
                return ServerResponse.createBySuccess();
            }
        }
        return ServerResponse.createByError();
    }

//    判断是否是商家
//    判断商家的状态
    @PostMapping("isseller")
    @ResponseBody
    public ServerResponse<String> msgIsSeller(){
        UseraccountDO useraccountDO = (UseraccountDO)HttpContextUtils.getHttpServletRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        HashMap<String , Object> map = new HashMap<>();
        map.put("uid",useraccountDO.getUid());
        List<SellerDO> sellerDOList =  sellerService.list(map);
        //判断是商家
        if(sellerDOList.size() > 0){
            //商家的状态
            SellerDO sellerDO = sellerDOList.get(0);
            return ServerResponse.createBySuccess(sellerDO.getStatus().toString());
        }
        return ServerResponse.createBySuccess("200001");
    }


    @PostMapping("msgmy")
    @ResponseBody
    public ServerResponse<MyUserInfo> msgMy(){
        return appUserInfoService.getMyUserInfo();
    }

    //获取我的推广会员的信息
    @ResponseBody
    @PostMapping("msgMyChildUser")
    public ServerResponse<PageUtils> msgMyChildUser(@RequestParam Map<String, Object> params) {
        UseraccountDO useraccountDO = (UseraccountDO) HttpContextUtils.getHttpServletRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        params.put("vuid",useraccountDO.getUid());
        //查看2级推广会员
        params.put("vLeave",3);

        Query query = new Query(params);
        List<UseraccountDO> userChildList = useraccountService.getUserChildList(query);
        int total = useraccountService.getCountUserChildList(query);
        PageUtils pageUtils = new PageUtils(userChildList, total);
        return ServerResponse.createBySuccess(useraccountDO.getUid().toString(),pageUtils);
    }
    //获取我的推广商家的信息
    @ResponseBody
    @PostMapping("msgMyChildSeller")
    public ServerResponse<PageUtils> msgMyChildSeller(@RequestParam Map<String, Object> params) {
        UseraccountDO useraccountDO = (UseraccountDO) HttpContextUtils.getHttpServletRequest().getSession().getAttribute(AppUtilXML.SESSION_CUSTOMER);
        params.put("vuid",useraccountDO.getUid());
        //查看2级推广商家
        params.put("vLeave",3);

        Query query = new Query(params);
        List<SellerDO> sellerChildList = useraccountService.getSellerChildList(query);
        int total = useraccountService.getCountSellerChildList(query);
        PageUtils pageUtils = new PageUtils(sellerChildList, total);
        return ServerResponse.createBySuccess(useraccountDO.getUid().toString(),pageUtils);
    }


    //身份认证图片上传
    @ResponseBody
    @PostMapping("fileuploadrenzheng")
    public ServerResponse fileuploadrenzheng(@RequestParam("file")MultipartFile file , HttpServletRequest request ,String fanzheng){
        UseraccountDO useraccountDO = (UseraccountDO)HttpContextUtils.getSessionObject(AppUtilXML.SESSION_CUSTOMER);
        FileDO fileDO = appUserInfoService.uploadUserImage(file,useraccountDO);

//        HashMap<String , Object> map = new HashMap<>();
//        map.put("uid",useraccountDO.getUid());
////        获取用户的详细信息
//        List<UserdetailsDO> userdetailsDOList = userdetailsService.list(map);
//        if(userdetailsDOList.size() < 1){
//            return ServerResponse.createByErrorMessage("身份证上传错误，请联系客服");
//        }
//        UserdetailsDO userdetailsDO = userdetailsDOList.get(0);

//        新建一个可以存放数据的用户详情对象
//        UserdetailsDO userd = new UserdetailsDO();
//        userd.setId(userdetailsDO.getId());
//        if(fanzheng.equals("zheng")){
//            userd.setZheng(fileDO.getUrl());
//        }else {
//            userd.setFan(fileDO.getUrl());
//        }
//        将照片信息存放
//        userdetailsService.update(userd);

        return ServerResponse.createBySuccess(fileDO);
    }













}
